package org.jeecg.modules.exProject.controller;

import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.modules.exChargeSetting.entity.ExChargeSetting;
import org.jeecg.modules.exChargeSetting.service.IExChargeSettingService;
import org.jeecg.modules.exProject.constant.ExProjectStepEnum;
import org.jeecg.modules.exProject.vo.ExProjectParam;
import org.jeecg.modules.exTenderAnnQuaInqueryAnn.entity.ExTenderAnnQuaInqueryAnn;
import org.jeecg.modules.exTenderAnnQuaInqueryAnn.service.IExTenderAnnQuaInqueryAnnService;
import org.jeecg.modules.exTenderFileClariModi.service.IExTenderFileClariModiService;
import org.jeecg.modules.exZbidOpeningArrange.entity.ExZbidOpeningArrange;
import org.jeecg.modules.exZbidOpeningArrange.service.IExZbidOpeningArrangeService;
import org.jeecg.modules.gcProject.vo.StatusEnum;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.service.ISysCategoryService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.exProject.entity.ExTenderProject;
import org.jeecg.modules.exProject.entity.ExSection;
import org.jeecg.modules.exProject.entity.ExProject;
import org.jeecg.modules.exProject.vo.ExProjectPage;
import org.jeecg.modules.exProject.service.IExProjectService;
import org.jeecg.modules.exProject.service.IExTenderProjectService;
import org.jeecg.modules.exProject.service.IExSectionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 立项项目
 * @Author: jeecg-boot
 * @Date: 2024-08-31
 * @Version: V1.0
 */
@Api(tags = "立项项目")
@RestController
@RequestMapping("/exProject/exProject")
@Slf4j
public class ExProjectController {
    @Autowired
    private IExProjectService exProjectService;
    @Autowired
    private IExTenderProjectService exTenderProjectService;
    @Autowired
    private IExSectionService exSectionService;
    @Autowired
    private IExZbidOpeningArrangeService iExZbidOpeningArrangeService;
    @Autowired
    private IExChargeSettingService iExChargeSettingService;
    /**
     * 招标公告
     */
    @Autowired
    private IExTenderAnnQuaInqueryAnnService iExTenderAnnQuaInqueryAnnService;
    /**
     * 招标文件
     */
    @Autowired
    private IExTenderFileClariModiService iExTenderFileClariModiService;
    @Autowired
    private ISysCategoryService sysCategoryService;
    /**
     * 分页列表查询
     *
     * @param exProject
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "立项项目-分页列表查询")
    @ApiOperation(value = "立项项目-分页列表查询", notes = "立项项目-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ExProject>> queryPageList(ExProject exProject,
                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                  HttpServletRequest req) {
        QueryWrapper<ExProject> queryWrapper = QueryGenerator.initQueryWrapper(exProject, req.getParameterMap());
        Page<ExProject> page = new Page<ExProject>(pageNo, pageSize);
        IPage<ExProject> pageList = exProjectService.page(page, queryWrapper);
        //行业分类字段展示
        for (ExProject section : pageList.getRecords()) {
            SysCategory sysCategory = sysCategoryService.getById(section.getIndustriesType());
            if (sysCategory != null) {
                section.setIndustryType(sysCategory.getName());
            }
        }
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param exProjectPage
     * @return
     */
    @AutoLog(value = "立项项目-添加")
    @ApiOperation(value = "立项项目-添加", notes = "立项项目-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ExProjectPage exProjectPage) {
        ExProject exProject = new ExProject();
        BeanUtils.copyProperties(exProjectPage, exProject);
        exProjectService.saveMain(exProject, exProjectPage.getExTenderProjectList(), exProjectPage.getExSectionList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param exProjectPage
     * @return
     */
    @AutoLog(value = "立项项目-编辑")
    @ApiOperation(value = "立项项目-编辑", notes = "立项项目-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ExProjectPage exProjectPage) {
        ExProject exProject = new ExProject();
        BeanUtils.copyProperties(exProjectPage, exProject);
        ExProject exProjectEntity = exProjectService.getById(exProject.getId());
        if (exProjectEntity == null) {
            return Result.error("未找到对应数据");
        }
        exProjectService.updateMain(exProject, exProjectPage.getExTenderProjectList(), exProjectPage.getExSectionList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "立项项目-通过id删除")
    @ApiOperation(value = "立项项目-通过id删除", notes = "立项项目-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        exProjectService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "立项项目-批量删除")
    @ApiOperation(value = "立项项目-批量删除", notes = "立项项目-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.exProjectService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "立项项目-通过id查询")
    @ApiOperation(value = "立项项目-通过id查询", notes = "立项项目-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ExProject> queryById(@RequestParam(name = "id", required = true) String id) {
        ExProject exProject = exProjectService.getById(id);
        if (exProject == null) {
            return Result.error("未找到对应数据");
        }
        SysCategory sysCategory=new SysCategory();
        sysCategory=sysCategoryService.getById(exProject.getIndustriesType());//获取这个树节点对象
        exProject.setIndustryType(sysCategory.getName());
        return Result.OK(exProject);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "招标项目通过主表ID查询")
    @ApiOperation(value = "招标项目主表ID查询", notes = "招标项目-通主表ID查询")
    @GetMapping(value = "/queryExTenderProjectByMainId")
    public Result<List<ExTenderProject>> queryExTenderProjectListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<ExTenderProject> exTenderProjectList = exTenderProjectService.selectByMainId(id);
        return Result.OK(exTenderProjectList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "标段（包）通过主表ID查询")
    @ApiOperation(value = "标段（包）主表ID查询", notes = "标段（包）-通主表ID查询")
    @GetMapping(value = "/queryExSectionByMainId")
    public Result<List<ExSection>> queryExSectionListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<ExSection> exSectionList = exSectionService.selectByMainId(id);
        return Result.OK(exSectionList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param exProject
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ExProject exProject) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<ExProject> queryWrapper = QueryGenerator.initQueryWrapper(exProject, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<ExProject> exProjectList = exProjectService.list(queryWrapper);

        // Step.3 组装pageList
        List<ExProjectPage> pageList = new ArrayList<ExProjectPage>();
        for (ExProject main : exProjectList) {
            ExProjectPage vo = new ExProjectPage();
            BeanUtils.copyProperties(main, vo);
            List<ExTenderProject> exTenderProjectList = exTenderProjectService.selectByMainId(main.getId());
            vo.setExTenderProjectList(exTenderProjectList);
            List<ExSection> exSectionList = exSectionService.selectByMainId(main.getId());
            vo.setExSectionList(exSectionList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "立项项目列表");
        mv.addObject(NormalExcelConstants.CLASS, ExProjectPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("立项项目数据", "导出人:" + sysUser.getRealname(), "立项项目"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ExProjectPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ExProjectPage.class, params);
                for (ExProjectPage page : list) {
                    ExProject po = new ExProject();
                    BeanUtils.copyProperties(page, po);
                    exProjectService.saveMain(po, page.getExTenderProjectList(), page.getExSectionList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    @AutoLog(value = "项目进场-提交送审")
    @ApiOperation(value = "项目进场-提交送审", notes = "项目进场-提交送审")
    @PostMapping(value = "/submitAudit")
    public Result<String> submitAudit(@RequestParam(name = "id", required = true) String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ExProject exProject = exProjectService.getById(id);
        if (exProject == null) {
            return Result.error("未找到对应数据");
        }
        SysCategory sysCategory=new SysCategory();
        sysCategory=sysCategoryService.getById(exProject.getIndustriesType());//获取这个树节点对象
        exProject.setIndustryType(sysCategory.getName());
        exProject.setStatus(StatusEnum.SUBMIT.getCode());
        exProject.setUpdateTime(new Date());
        exProject.setUpdateBy(sysUser.getUsername());
        exProjectService.updateById(exProject);
        return Result.OK("提交送审成功!");
    }

    @AutoLog(value = "项目进场-审核")
    @ApiOperation(value = "项目进场-审核", notes = "项目进场-审核")
    @PostMapping(value = "/audit")
    public Result<String> audit(@RequestBody ExProjectParam exProjectParam) {
        exProjectService.audit(exProjectParam);
        return Result.OK("审核成功!");
    }

    @AutoLog(value = "项目进场-项目进度")
    @ApiOperation(value = "项目进场-项目进度", notes = "项目进场-项目进度")
    @GetMapping(value = "/process")
    public Result<Map> process(@RequestParam(name = "id", required = true) String id) {
        Map map = new HashMap();
        map.put("xmxx", 1);//项目信息
        map.put("cdyy", 0);//场地预约
        map.put("zfdy", 0);//资费定义
        map.put("zbgg", 0);//招标公告
        map.put("zbwj", 0);//招标文件
        ExProject exProject = this.exProjectService.getById(id);
        if (Objects.nonNull(exProject) && StatusEnum.SUCCESS.getCode().equals(exProject.getStatus())) {
            map.put("cdyy", 1);
        }
        if (map.get("xmxx").equals(1)) {
            LambdaQueryWrapper<ExZbidOpeningArrange> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ExZbidOpeningArrange::getProjectId, id);
            List<ExZbidOpeningArrange> exZbidOpeningArranges = iExZbidOpeningArrangeService.list(queryWrapper);
            if (CollectionUtil.isNotEmpty(exZbidOpeningArranges)) {
                if (exZbidOpeningArranges.stream().filter(obj -> StatusEnum.SUCCESS.getCode().equals(obj.getStatus())).count() > 0) {
                    map.put("zfdy", 1);
                }
            }
        }
        if (map.get("zfdy").equals(1)) {
            LambdaQueryWrapper<ExChargeSetting> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ExChargeSetting::getProjectId, id);
            List<ExChargeSetting> exChargeSettingList = iExChargeSettingService.list(queryWrapper);
            if (CollectionUtil.isNotEmpty(exChargeSettingList)) {
                if (exChargeSettingList.stream().filter(obj -> StatusEnum.SUCCESS.getCode().equals(obj.getStatus())).count() > 0) {
                    map.put("zbgg", 1);
                }
            }
        }
        if (map.get("zbgg").equals(1)) {
            LambdaQueryWrapper<ExTenderAnnQuaInqueryAnn> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ExTenderAnnQuaInqueryAnn::getProjectId, id);
            List<ExTenderAnnQuaInqueryAnn> exTenderAnnQuaInqueryAnnList = iExTenderAnnQuaInqueryAnnService.list(queryWrapper);
            if (CollectionUtil.isNotEmpty(exTenderAnnQuaInqueryAnnList)) {
                if (exTenderAnnQuaInqueryAnnList.stream().filter(obj -> StatusEnum.SUCCESS.getCode().equals(obj.getStatus())).count() > 0) {
                    map.put("zbwj", 1);
                }
            }
        }
        return Result.OK("", map);
    }




    @AutoLog(value = "项目进场-项目进度")
    @ApiOperation(value = "项目进场-项目进度", notes = "项目进场-项目进度")
    @GetMapping(value = "/queryStep")
    public Result<Integer> queryProjectStep(@RequestParam(name = "id", required = true) String id) {
        ExProject exProject = this.exProjectService.getById(id);
        if (null == exProject) {
            return Result.OK("", ExProjectStepEnum.WAIT_AUDIT.getValue());
        }
        if (null == exProject.getStep()) {
            return Result.OK("", ExProjectStepEnum.WAIT_AUDIT.getValue());
        }
        return Result.OK("", exProject.getStep());
    }
}
